package com.alen.sun.interceptor;

import com.alen.sun.bean.Elderly;
import com.alen.sun.bean.Employee;
import com.alen.sun.util.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class ElderlyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            // 处理预检请求，设置允许跨域访问的响应头
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
            response.setHeader("Access-Control-Max-Age", "3600");  // 预检请求的有效期，单位秒
            log.info("预处理前端请求");
            return false;  // 终止请求，不再传递给控制器
        } else {
            // 处理实际请求
            String token = request.getHeader("Authorization");
            System.out.println("---------");
            System.out.println(token);
            System.out.println("---------");

            if (token != null && token.startsWith("Bearer")) {
                token = token.substring(7);  // 去掉"Bearer"
                Claims claims = JwtUtils.parseJWT(token);
                Employee employee = new ObjectMapper().convertValue(claims.get("employee"), Employee.class);
                if (employee == null) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    return false;
                }
                request.setAttribute("employee", employee);
                return true;  // 继续传递请求给控制器
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                log.info("进入拦截器，但未查询到token");
                return false;
            }
        }
    }
}
